<template>
    <div>
        <template v-for="menu in menus">
            <template v-if="menu.hidden"/>
            <template v-else-if="(!menu.children || menu.children.length === 0)">
                <el-menu-item :index="menu.menuKey" @click="jumpToView(menu)">
                    <img :src="getIconUrl(menu)" alt="" :class="['router-icon', collapsed ? 'collapsed-icon' : '']" v-if="menu.icon">
                    <template v-if="!collapsed">{{displayMenuName(menu)}}</template>
                </el-menu-item>
            </template>
            <template v-else-if="!menu.leaf">
                <el-submenu :index="menu.menuKey" :key="menu.menuId">
                    <template slot="title">
                        <img :src="getIconUrl(menu)" alt="" :class="['router-icon', collapsed ? 'collapsed-icon' : '']" v-if="menu.icon">
                        <template v-if="!collapsed">{{displayMenuName(menu)}}</template>
                    </template>
                    <commons-menu :value="menu.children" @jumpToView="jumpToView"/>
                </el-submenu>
            </template>
            <template v-else-if="menu.children && menu.children.length > 0">
                <el-menu-item :index="menu.children[0].name" @click="jumpToView(menu.children[0])">
                    <img :src="getIconUrl(menu)" alt="" :class="['router-icon', collapsed ? 'collapsed-icon' : '']" v-if="menu.icon">
                    <template v-if="!collapsed">{{displayMenuName(menu)}}</template>
                </el-menu-item>
            </template>
        </template>
    </div>
</template>
<script lang="ts">
  import Menu from '@/structure/menu';
  import {Component, Prop, Vue, Watch} from 'vue-property-decorator';

  @Component
  export default class CommonsMenu extends Vue {
    @Prop({
      required: true
    })
    public value!: Menu[];
    @Prop({
      required: false,
      default: false
    })
    public collapsed!: boolean;
    public menus: Menu[] = [];

    public created(): void {
      this.menus = this.value;
    }

    @Watch('value')
    public valueChangeHandler(val: Menu[]): void {
      this.menus = val || [];
    }

    public getIconUrl(item: Menu): string {
      return this.$getImageUrl(item.icon as string);
    }

    public displayMenuName(item: Menu): string {
      return item.displayName ? item.displayName : item.menuKey;
    }

    public jumpToView(menu: Menu): void {
      this.$emit('jumpToView', menu);
    }
  }
</script>
<style>
    .collapsed>.el-menu>div>.el-submenu>.el-submenu__title>.el-submenu__icon-arrow:before {
        content: "" !important;
    }
</style>
